package cn.kbyue.security.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * 环境感知设定
 *
 * @author xl
 * @date 2020/4/25 13:56
 */
@Slf4j
@Component
public class Env implements ApplicationListener<ApplicationStartedEvent> {

    private final String dev_profile_name = "dev";
    private final String test_profile_name = "test";
    private final List<String> online_profile_name = Arrays.asList("online", "prod");

    public static boolean isDev = false;
    public static boolean isTest = false;
    public static boolean isDebug = false;
    public static boolean isOnline = false;

    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        log.info(">>> application started");

        String[] activeProfiles = event.getApplicationContext().getEnvironment().getActiveProfiles();
        setEnv(activeProfiles);
    }

    private void setEnv(String[] activeProfiles) {
        List<String> actives = Arrays.asList(activeProfiles);
        if (actives.contains(dev_profile_name)) {
            Env.isDev = true;
        } else if (actives.contains(test_profile_name)) {
            Env.isTest = true;
        }
        if (actives.contains(dev_profile_name) || actives.contains(test_profile_name)) {
            Env.isDebug = true;
        } else if (actives.containsAll(online_profile_name)) {
            Env.isOnline = true;
        } else {
            log.warn(">>> 未知环境: {}", Arrays.asList(activeProfiles));
        }
    }

}
